<template>
  <yt-crud
  ref="crudRef" :data="data" :column="column"
  :loading="state.loading"
  :total="state.total"
  v-model:page="state.page"
  v-model:query="state.query"
  :tableProps=" {
    selection: true,
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    menuSlot: true,
    menuWidth: 120,
  }"
  :funProps="{
    addBtn: false,
    delBtn: true,
    delBtnText: '批量退组'
  }"
  @on-load="getData"
  @delFun="onDelete"
  >
      <template #operate="scope">
        <el-button size="small" type="primary" plain @click="handleOperate(scope.row)" :disabled="!scope.row.product || scope.row.deviceQty == 0" v-hasPermi="['iot:deviceGroup:ctrl']">控制</el-button>
      </template>
      <template #menuSlot="scope">
        <el-button type="text" size="small" @click="removeFromGroup(scope.row.id)">退组</el-button>
      </template>

      <template #type="{ row }">{{ getNodeTypeName(row.product) }}</template>
      <template #online="scope">
        <el-tag class="state" v-if="scope.row.online === true" type="success" size="small">在线</el-tag>
        <el-tag class="state" v-else-if="scope.row.online === false" type="danger" size="small">离线</el-tag>
      </template>
      <template #deviceCustomName="{ row }">{{ row.deviceCustomName || '未定义' }}</template>
      <template #uid="{ row }">{{ getUserName(row.uid) }}</template>

      <template #group="scope">
        <el-tag v-for="i,k in scope.row.group" :key="k">{{ i.name }}</el-tag>
      </template>
  </yt-crud>
  <!-- 4G灯控制电源(新创)操作页面 -->
  <swSl ref="sw_slRef" />
  <!-- 微自然网关操作页面 -->
  <wzrGateway ref="wzr_gatewayRef" />
  <!-- 技象Lora网关操作页面 -->
  <el-dialog
    title="分组设置"
    v-model="state.showJxLoraGateway"
    width="700px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <jxLoraGateway ref="jx_lora_gatewayRef" :row="state.currentRow" />
  </el-dialog>
  <!-- 光照度传感器 -->
  <opticalSensor ref="opticalSensorRef" />
</template>
<script lang="ts" setup>
import { ComponentInternalInstance } from 'vue'

import { IColumn } from '@/components/common/types/tableCommon'
import YtCrud from '@/components/common/yt-crud.vue'

import { getDevicesList, removeDeviceFromDeviceGroup } from './api/devices.api'
import { getProductsList, IProductsVO } from './api/products.api'
import { listUser } from '@/api/system/user/index'

import swSl from './components/sw_sl.vue'
import wzrGateway from './components/wzr_gateway.vue'
import jxLoraGateway from './components/jxLoraGateway.vue'
import opticalSensor from './components/opticalSensor.vue'
// 引入公共方法判断设备
import { isLightController, isOpticalSensor } from '@/utils/deviceUtils'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const route = useRoute()
const { id } = route.params

const column = ref<IColumn[]>([
  {
    label: '控制',
    key: 'operate',
    formHide: true,
    slot: true,
    tableWidth: 80,
    align: 'center'
  },
  {
    label: '设备ID',
    key: 'deviceId',
    hide: true,
  },
  {
    label: '设备自定义名称',
    key: 'deviceCustomName',
    slot: true,
  },
  {
    label: '产品',
    key: 'productKey',
    type: 'select',
    search: true,
    colSpan: 12,
    tableWidth: 200,
    editDisabled: true,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'productKey',
      options: [],
    },
  },
  {
    label: '设备类型',
    key: 'type',
    slot: true,
    tableWidth: 120,
    componentProps: {
      labelAlias: 'nickName',
      valueAlias: 'id',
      options: [],
    },
  },
  {
    label: '关键字',
    key: 'keyword',
    formHide: true,
    hide: true,
    search: true,
  },
  {
    label: '设备DN',
    key: 'deviceName',
    tableWidth: 240
  },
  {
    label: '分组',
    key: 'group',
    slot: true,
  },
  {
    label: '所属用户',
    key: 'uid',
    formHide: true,
    slot: true,
    tableWidth: 120,
    componentProps: {
      labelAlias: 'nickName',
      valueAlias: 'id',
      options: [],
    },
  },
  {
    label: '状态',
    key: 'online',
    type: 'select',
    componentProps: {
      options: [
        {
          label: '在线',
          value: true,
        },
        {
          label: '离线',
          value: false,
        },
      ],
    },
    search: false,
    tableWidth: 80,
    slot: true,
  },
  {
    label: '创建时间',
    key: 'createAt',
    tableWidth: 180,
    sortable: true,
    type: 'date',
  },
])

const data = ref()

const state = reactive({
  page: {
    pageSize: 10,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {
    group: id
  },
  showJxLoraGateway: false, // 控制技象Lora网关弹窗显示
  currentRow: null, // 当前选中的技象Lora网关设备行数据
})

/** 控制按钮操作 */
const sw_slRef = ref()
const wzr_gatewayRef = ref()
const jx_lora_gatewayRef = ref()
const opticalSensorRef = ref()
const handleOperate = (row: any) => {  
  if (isLightController(row.productKey)) {
    sw_slRef.value.openDialog(row)
  }
  else if (row.productKey === '7GhmGTj27mehmpaJ') { // 微自然网关
    wzr_gatewayRef.value.openDialog(row)
  } 
  else if (row.productKey === 'sfFiZ4Xmd5axJt3Y') { // 技象Lora网关
    state.currentRow = row
    state.showJxLoraGateway = true
  }
  else if (isOpticalSensor(row.productKey)) { // 光照度传感器
    opticalSensorRef.value.openDialog(row)
  }
}

// 产品字典
const productOptions = ref<IProductsVO[]>([])
const getDict = () => {
  getProductsList({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    productOptions.value = res.data.rows || []
    column.value.forEach((item) => {
      if (item.key === 'productKey') {
        item.componentProps.options = productOptions.value
      }
    })
  })
}
getDict()

// 获取设备类型
const getNodeTypeName = (p) => {
  if (!p) {
    return '直连设备'
  }
  const nodeType = p.nodeType ? p.nodeType : 0
  return ['网关设备', '网关子设备', '直连设备'][nodeType]
}

// 获取用户下拉框数据
const userOptions = ref<any[]>([])
const getUserList = async () => {
  const res: any = await listUser(proxy?.addDateRange({pageNum: 1,pageSize: 999,},['', '']))
  userOptions.value = res.data.rows || []
}
getUserList()
// 获取用户名称
const getUserName = (userId) => {
  const user = userOptions.value.find(u => u.id == userId)
  return user? user.nickName : ''
}

const getData = () => {
  state.loading = true
  getDevicesList({
    ...state.page,
    ...state.query}).then(res => {
      data.value = res.data.rows
      state.total = res.data.total
  }).finally(() => state.loading = false)
}


// removeFromGroup 退组
const removeFromGroup = (deviceId: string) => {

  removeDeviceFromDeviceGroup({group: id, devices: [deviceId]}).then(res => {
    // 退组成功
    if (res.code == 200 ) {
      ElMessage.success('退组成功!')
      getData()
    }
  })
}


// 删除
const onDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    await removeDeviceFromDeviceGroup({group: id, devices: row.map((m) => m.id)})
  } else {
    await removeDeviceFromDeviceGroup({group: id, devices: [row.id]})
  }
  ElMessage.success('退组成功!')
  state.loading = false
  getData()
}

</script>

<!-- <style lang="scss" scoped>

</style> -->
